<!--  
 * 项目管理 - 右侧抽屉新增编辑内容
 * @author: 张锋
 * @since: 2025-02-10
 * index.vue
-->
<template>
  <div class="offsideDrawer">
    <el-drawer v-model="isShowDrawer" title="" :before-close="closedDrawer">
      <template #title>
        <div class="drawer-title">
          <div class="title-icon"></div>
          <div class="title-text">
            <span>{{ drawer.title }}</span>
          </div>
        </div>
      </template>
      <template #default>
        <el-form class="drawer-content" :model="form" :rules="rules" ref="validateform">
          <el-form-item label="项目名称：" prop="projectName" class="projectsname">
            <inputCustom :model="form.projectName" placeholder="请输入项目名称" :maxLength="64" @inputEvent="inputprojectsname"></inputCustom>
          </el-form-item>
          <el-form-item label="项目描述：" prop="projectDesc">
            <el-input v-model="form.projectDesc" type="textarea" placeholder="请输入项目描述" :rows="6" />
          </el-form-item>
          <el-form-item label="所在地：" prop="provinceName">
            <ChooseAddress width="" :showDetailAddress="false" @changeAddress="changeAddress"></ChooseAddress>
          </el-form-item>
          <el-form-item label="详细地址：" prop="addressDetaill">
            <el-input v-model="form.addressDetaill" placeholder="请输入项目地址"></el-input>
          </el-form-item>
          <el-form-item label="项目经理：" prop="projectOperId">
            <el-select v-model="form.projectOperId">
              <el-option :label="item.realName" :value="item.userName" v-for="item in state.userList" :key="item.userName" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划完成日期：" prop="projectPlanDate">
            <el-date-picker v-model="form.projectPlanDate" type="date" placeholder="请输入计划完成日期" :size="size" />
          </el-form-item>
          <el-form-item v-if="props.ProjectsId" label="施工档案">
            <ul>
              <li v-for="(item,index) in data.fileArray" :key="item">
                <a :href="item">施工档案{{ index + 1 }}</a>
              </li>
            </ul>
          </el-form-item>
          
          <el-form-item v-if="props.ProjectsId" label="上传施工档案">
            <el-upload :multiple="false" :file-list="state.fileList" class="upload-demo" 
            drag :http-request="uploadHttpRequest" :show-file-list="true" :before-upload="checkFile"
            :on-remove="removeFile">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                将文件拖拽至此 /
                <em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" size="mini" style="width: 100px" @click="save">提交</el-button>
          <el-button size="mini" style="width: 100px" @click="closedDrawer">取消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { reactive, ref, defineProps, defineEmits, onMounted, watch, inject } from 'vue'
import { getAllMenuList, addProject, editRole, getInfo } from '@/api/interface/projects.js'
import { getUserListApi } from '@/api/interface/userManage.js'
import { uploadFilePathApi, dowloadOtherFileApi } from '@/api/public/uploadFile.js'

import { successHandle, recursiveId } from '@/utils/common.js'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const store = useStore()
const router = useRouter()
const props = defineProps({
  isShowDrawer: {
    //是否展开项目抽屉
    type: Boolean,
    default: false,
  },
  ProjectsId: [String],
  data: {
    //row数据
    type: Object,
    default: () => {},
  },
})

const emits = defineEmits(['close', 'refresh'])
const reload = inject('reload')
const state = reactive({
  allMenuList: [], //所有菜单数据
  selectAllIdList: [], //选中的所有menuIdList
  userList: [],
  fileList: [],
  choosedFileList: [],

})
const drawer = reactive({
  title: '新增',
})
//新增编辑 form
const form = reactive({
  projectName: '', //项目名称
  addressDetaill: '', //项目地址
  projectOperId: '', //项目责任人
  projectOperName: '', //项目责任人
  projectPlanDate: '', //项目计划完成日期
  projectDesc: '', //项目描述
  provinceName: '',
  cityName: '',
  areaName: '',
})

onMounted(() => {
  getAllMenu()
  getUserList()
})
//watch监听
watch(
  () => props.ProjectsId,
  (val) => {
    if (val) {
      for (let key in form) {
        form[key] = props.data[key]
      }
      drawer.title = '编辑'
      getCurrentProjectsMenuPermission(props.ProjectsId)
    }
  }
)

//获取地址
const changeAddress = (info) => {
  form.addressProvince = info.provinceName
  form.addressCity = info.cityName
  form.addressArea = info.areaName
}
//表单验证
const rules = {
  projectName: [{ required: true, message: '必填项', trigger: 'blur' }],
  addressProvince: [{ required: true, message: '必填项', trigger: 'blur' }],
  addressDetaill: [{ required: true, message: '必填项', trigger: 'blur' }],
  projectDesc: [{ required: true, message: '必填项', trigger: 'blur' }],
  projectOperId: [{ required: true, message: '必填项', trigger: 'blur' }],
  projectPlanDate: [{ required: true, message: '必填项', trigger: 'blur' }],
}
//获取注册用户列表
const getUserList = () => {
  const params = {
    ipi: 1,
    ips: 999,
    roleId: '95eaf4b548c34c4fb2726606112324b0',
  }
  getUserListApi(params).then((res) => {
    const { status, data } = res
    if (status == 200) {
      state.userList = data.result
    }
  })
}
//表单元素
const validateform = ref(null)

//树 dom
const tree = ref(null)


//获取所有的菜单数据
const getAllMenu = () => {
  getAllMenuList().then((res) => {
    const { status, data } = res
    if (status === 200) {
      state.allMenuList = data
    }
  })
}

//获取当前项目菜单的权限
const getCurrentProjectsMenuPermission = async (id) => {
  await getInfo({ id: id }).then((res) => {
    const { status, data } = res
    if (status === 200) {
      const selectArr = recursiveId(data)
      selectArr.forEach((item) => {
        tree.value.setChecked(item, true, false)
      })
    }
  })
}

//选择项目权限配置数据
const selectTree = (data, checked) => {
  state.selectAllIdList = tree.value.getCheckedKeys().concat(tree.value.getHalfCheckedKeys())
}

//项目名称输入事件
const inputprojectsname = (text) => {
  form.projectName = text
}

//关闭抽屉 清空数据
const closedDrawer = () => {
  validateform.value.resetFields()
  emits('close')
  tree.value.getCheckedNodes().some((item) => {
    tree.value.setChecked(item.id, false, true)
  })
  for (let key in form) {
    form[key] = ''
  }
  drawer.title = '新增'
}
//新增项目调用接口
const postaddRole = (data) => {
  addProject(data).then((res) => {
    successHandle(res)
    closedDrawer()
    emits('refresh')
  })
}

//修改项目调用接口
const puteditRole = (params) => {
  editRole(params).then(async (res) => {
    successHandle(res)
    closedDrawer()
    emits('refresh')
    if (res.status === 200) {
      reload()
      await store.dispatch('user/getMenuList')
      await store.dispatch('routes/setAllRoutes').then((res) => {
        res.forEach((item) => {
          router.addRoute(item)
        })
      })
    }
  })
}

//上传文件
const uploadFile = (data) => {}
//下载文件
const downloadFile = () => {
  dowloadOtherFileApi({ dataType: 'DEMAND' }).then((res) => {
    console.log(res)
    fileDownload(
      {
        fileSuffix: 'xlsx',
        name: '技术需求导入模板',
      },
      res
    )
  })
}

//上传文件
const uploadHttpRequest = (data) => {
  let fd = new FormData()
  fd.append('file', data.file)
  console.log("data.file",data.file);
  uploadFilePathApi(fd).then((res) => {
    state.choosedFileList.push({path: res.data,name:data.file.name})
    ElMessage.success('上传成功！')
  })
}

//选择文件
const checkFile = (data) => {
  let index = data.name.lastIndexOf('.')
  let type = data.name.slice(index + 1)
  if (type != 'doc' && type != 'docx') {
    ElMessage.error('不是合法的文件格式')
    return false
  }
}
//删除文件
const removeFile = (file, files) => {
  state.choosedFileList = state.choosedFileList.filter(item => item.name !== file.name);
}

//保存
const save = () => {
  validateform.value.validate((valid) => {
    if (valid) {
      state.userList.map((item) => {
        if (item.userName == form.projectOperId) {
          form.projectOperName = item.realName
        }
      })
      if (props.ProjectsId) {
        let fileArray = []
        state.choosedFileList.map( item => {
          fileArray.push(item.path)
        })
        //修改
        console.log('修改')
        const params = {
          id: props.ProjectsId,
          ...form,
          fileArray: fileArray
        }
        puteditRole(params)
        emits('refresh')
        emits('close')
      } else {
        //新增
        console.log('没有id，新增')
        const params = {
          ...form,
        }
        postaddRole(params)
        emits('refresh')
        emits('close')
      }
    } else {
      console.log('没通过验证')
    }
  })
}


</script>
<style lang="scss" scoped>
.el-form-item__content {
  width: 100%;
}

.projectsname {
  margin-bottom: 0;

  :deep(.el-form-item__error) {
    top: 90%;
  }
}
</style>
